<template>
  <DialogLayout ref="dialogRef" method="POST" path="/dev-api/oa/headcount" @submited="handlerDialogSubmited">
    <el-form-item label="时间段" prop="timeSlot">
      <el-date-picker readonly v-model="form.timeSlot" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
    </el-form-item>
    <el-form-item label="部门" prop="deptIds">
      <el-cascader :options="deptList" :props="deptProps" v-model="form.deptIds" style="width: 100%" />
    </el-form-item>
    <el-form-item label="人数" prop="userNum">
      <el-input v-model="form.userNum" autocomplete="off" type="number" />
    </el-form-item>
  </DialogLayout>
</template>
<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import DialogLayout from '../../layout/DialogLayout.vue'
import { FormRules } from 'element-plus'
import { useDeptStore, useUsersStore } from '../../stores'
import { formatDate, getWeeksBetweenDates } from '../../utils'
import http from '../../http'
import { ElMessage } from 'element-plus'

const emits = defineEmits(['submited'])
const deptProps = ref({ label: 'deptName', value: 'deptId' })
const deptList = ref(useDeptStore().getAllState())
const dialogRef = ref<InstanceType<typeof DialogLayout>>()
const userNumRows = ref<Record<string, any>>({})
const form = reactive({
  id: null,
  weekStartDate: '',
  weekEndDate: '',
  deptIds: [] as number[],
  deptId: -1,
  deptName: '',
  userNum: 0,
  createBy: useUsersStore().user.username,
  timeSlot: [] as Date[],
})

watch(
  () => form.deptIds,
  () => {
    // console.log('userNumRows.value', userNumRows.value)
    const item = useDeptStore().getDeptById(form.deptIds[2])
    // console.log('item', item)
    if (item) {
      const item2 = userNumRows.value[`${item.deptId}-${item.deptName}`]
      // console.log('item2', item2)
      if (item2) {
        form.userNum = item2.userSum
      }
    }
  }
)

/**
 * 验证时间区间是否被占用
 *
 * @param rule 校验规则
 * @param value 校验值，应为包含两个时间戳的数组 [startTime, endTime]
 * @param callback 回调函数，验证通过时传入null，验证失败时传入错误信息
 */
const validateTimeSlot = (rule: any, value: any, callback: any) => {
  console.log('rule', rule)

  if (!value[0] && !value[1]) {
    callback(new Error('请选择时间段'))
  } else {
    callback()
  }
}
/**
 * 验证时间区间是否被占用
 *
 * @param rule 校验规则
 * @param value 校验值，应为包含两个时间戳的数组 [startTime, endTime]
 * @param callback 回调函数，验证通过时传入null，验证失败时传入错误信息
 */
const validateDept = (rule: any, value: any, callback: any) => {
  console.log('rule', rule)

  if (value.length < 3) {
    callback(new Error('请选择部门'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  timeSlot: [
    { required: true, validator: validateTimeSlot, trigger: 'change' },
    { required: true, validator: validateTimeSlot, trigger: 'blur' },
  ],
  deptIds: [
    { required: true, validator: validateDept, trigger: 'change' },
    { required: true, validator: validateDept, trigger: 'blur' },
  ],
  userNum: [
    {
      required: true,
      validator: (rule: any, value: number, callback: any) => {
        console.log('rule', rule)
        if (value < 0) {
          callback(new Error('人数必须大于等于 0'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

/**
 * 构建请求参数
 *
 * @param start 开始日期
 * @param end 结束日期
 * @returns 请求参数对象
 */
const buildParams = (start: any, end: any) => {
  console.log('weeks', start, end)
  form.deptId = form.deptIds[form.deptIds.length - 1]
  const deptItem = useDeptStore().getDeptById(form.deptId)
  // form.deptName = deptItem.deptName
  // form.weekStartDate = start
  // form.weekEndDate = end
  return {
    weekStartDate: start,
    weekEndDate: end,
    deptId: form.deptId,
    deptName: deptItem.deptName,
    userNum: form.userNum,
    createBy: form.createBy,
  }
}

const openDialog = (val: any) => {
  const { startDate, endDate, userNum, numRows } = val
  userNumRows.value = numRows
  console.log('userNumRows', userNumRows)
  console.log('userNumRows.value', userNumRows.value)
  form.timeSlot = [startDate, endDate]
  form.userNum = userNum
  dialogRef.value?.openDialog({
    title: '添加员工',
    class: 'dialog-add-headcount',
    form: form,
    rules: rules,
    submitFunction: async (callback: Function) => {
      const currentDate = new Date(startDate)
      currentDate.setFullYear(currentDate.getFullYear() + 1)
      const weeks = getWeeksBetweenDates(startDate, currentDate)
      const res: any = []

      weeks.forEach(async (week: any) => {
        const params = buildParams(formatDate(week.start, 'yyyy-MM-dd'), formatDate(week.end, 'yyyy-MM-dd'))
        res.push(http({ method: 'POST', path: '/dev-api/oa/headcount', params }))
      })
      const requesets = await Promise.all(res)
      const result = requesets.reduce(
        (acc: any, obj: any) => {
          if (obj.code === 200) {
            acc.count200++
          }
          if (obj.code === 500) {
            acc.count500++
          }
          return acc
        },
        { count200: 0, count500: 0 }
      )
      if (weeks.length === result.count200) {
        ElMessage({
          message: `添加成功！`,
          grouping: true,
          type: 'success',
        })
      } else {
        ElMessage({
          message: `添加失败！成功：${result.count200}，失败：${result.count500}`,
          grouping: true,
          type: 'error',
        })
      }
      await callback()
    },
  })
}

const handlerDialogSubmited = (data: any) => {
  emits('submited', data)
}

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped></style>
